package wox.lonice.utis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import wox.lonice.dto.wechat.WeArticle;
import wox.lonice.dto.wechat.WePublic;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * 爬虫
 */
public class ReptileUtils {

    public static void main(String[] args) {

//        System.out.println(WxUtils.getWXToken());


        //获取公众号信息
        String publicUrl = "https://mp.weixin.qq.com/cgi-bin/searchbiz";
        String cookie = "noticeLoginFlag=1; bizuin=3870238608; slave_sid=YWdrTXdNYVVGN3JmUkhPSzVIYzlZQWJQX0VSN2NzUjB2WUJaaGRDcEI3Slp3YzZaelhTMHlOSGFNQXJ1N1M2STV5eVZEXzRMRGNPZzdKbTJwY1BsWThaZE5BTFBiVWowUGowYTRWdWxVZnBtMDdaNDJjZzI1NDJwOWx2bXFPeXFWdGRodXIwenFqekpyNFNH; slave_user=gh_52bbc1f5859f; data_bizuin=3870238608; data_ticket=vWokXaqspOcUHlUhRiOW1QjabwzAHoEsYtUC7HCI2/Of4jEYdfXlzcXJQRlb1KC/; mm_lang=zh_CN; openid2ticket_okCev5syaGasu9oEVj8eW2qdcGFE=rErUKzQ26FoXz45hC8Qsw1JBa6rBqWbh9H3a2ANmI1E=; ua_id=9cwkJcpB87jCbpy9AAAAAHlGwcpJNsX2nSptEkEzAWk=; xid=96a6dd444ad75c1b94f67c0634ceb365; ticket=a41ec4e00b8ef33f5576765e38ee901ec45004f9; ticket_id=gh_52bbc1f5859f; uuid=2ed1a17bc4e785cccb8c76fe7e33f7c2; rewardsn=; wxtokenkey=777; noticeLoginFlag=1; sig=h019fb3de6a7eccb91f14453016e07c93f8df1d6578d47623fdf3b85f147b47cbb3fe883476bdc910a3; pgv_info=ssid=s2469411440; pgv_pvid=1200423636; cert=jz_HprhT8nHYm_NpYjHVhEHYyVVtKWn7; pgv_pvi=6588509184; pgv_si=s7691920384";

        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("action", "search_biz");
        paramMap.put("token", "1083424310");
        paramMap.put("lang", "zh_CN");
        paramMap.put("f", "json");
        paramMap.put("ajax", 1);
        paramMap.put("random", Math.random());
        paramMap.put("query", "ss");
        paramMap.put("begin", 0);
        paramMap.put("count", 10);

        String publicResult = sendGet(cookie, publicUrl, BeanUtil.getUrlParamsByMap(paramMap));
        JSONObject publicJsonObject = JSONObject.parseObject(publicResult);
        if ("ok".equalsIgnoreCase(publicJsonObject.getJSONObject("base_resp").getString("err_msg"))) {
            JSONArray publicJsonArray = publicJsonObject.getJSONArray("list");
            List<WePublic> wePublics = publicJsonArray.toJavaList(WePublic.class);
            System.out.println(wePublics);
        }

        String articleUrl = " https://mp.weixin.qq.com/cgi-bin/appmsg";

        paramMap = Maps.newHashMap();
        paramMap.put("action", "list_ex");
        paramMap.put("token", "1083424310");
        paramMap.put("lang", "zh_CN");
        paramMap.put("f", "json");
        paramMap.put("ajax", 1);
        paramMap.put("random", Math.random());
        paramMap.put("query", "");
        paramMap.put("begin", 0);
        paramMap.put("count", 10);
        paramMap.put("fakeid", "MzU4NTEwNzQwOQ==");
        paramMap.put("type", "9");

        String articleResult = sendGet(cookie, articleUrl, BeanUtil.getUrlParamsByMap(paramMap));
        JSONObject articleJsonObject = JSONObject.parseObject(articleResult);
        if ("ok".equalsIgnoreCase(articleJsonObject.getJSONObject("base_resp").getString("err_msg"))) {
            JSONArray articleJsonArray = articleJsonObject.getJSONArray("app_msg_list");
            List<WeArticle> weArticles = articleJsonArray.toJavaList(WeArticle.class);
            System.out.println(weArticles);
        }


    }


    public static String sendGet(String cookie, String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            if (StringUtils.isNotEmpty(param)) {
                urlNameString = urlNameString + "?" + param;
            }
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            //cookie
            if (StringUtils.isNotEmpty(cookie)) {
                conn.setRequestProperty("Cookie", cookie);
            }
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15");
            // 建立实际的连接
            conn.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = conn.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
